package com.lyh.hkcloud.module.m1300090;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.lyh.hkcloud.R;
import com.lyh.hkcloud.adapter.AutoCompleteTextViewAdapter;
import com.lyh.hkcloud.constants.BusinessConstants;
import com.lyh.hkcloud.constants.HttpUrlComstants;
import com.lyh.hkcloud.module.m1300085.service.Service;
import com.lyh.hkcloud.util.base.JsonUtil;
import com.lyh.hkcloud.util.base.SaveData;
import com.lyh.hkcloud.util.base.StringUtils;
import com.lyh.hkcloud.util.base.ToastUtils;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * //{"dataIds":["1563469462613524482"],"data":[{"id":"1563469462613524482","num":"1"}],"maindata":{"field_6887600017549299712":"一期工业园办公楼131303","field_6887600017540911109":"Q1-B3-13F-1303"},"userid":"1465136442656292864","username":"温文亮"}
 *
 * @author: wenwenliang
 * @description: 更新位置资产信息
 * @date: 2023-11-27 14:01
 **/
public class UpdateLocationActivity extends AppCompatActivity implements View.OnClickListener {

    private Service service;
    /**
     * 单号
     */
    private TextView tvInventoryNo;
    /**
     * 实物码
     */
    private TextView tvCardNumber;
    /**
     * 位置下拉框
     */
    private AutoCompleteTextView atvLocationNumber;

    /**
     * 位置下拉框数据(第一次打开页面即赋值)
     */
    List<String> locationArray;

    private ImageView goBack;
    /**
     * 保存按钮
     */
    private Button btSave;
    /**
     * 取消按钮
     */
    private Button btCancel;

    /**
     * 当前实物码资产信息数据(每次打开页面查询)
     */
    private List<Map<String, Object>> faCardInfo = new ArrayList<>();
    /**
     * 代码提交信息提示组件
     */
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //调接口服务
        service = new Service(UpdateLocationActivity.this);
        //加载布局
        setContentView(R.layout.activity_1300090_location);
        //去除页头
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        //组件初始化
        initAssembly();
    }

    @Override
    protected void onStart() {
        super.onStart();
        //赋值实物码
        Intent intent = getIntent();
        String cardNumber = intent.getStringExtra("cardNumber");
        String inventoryNo = intent.getStringExtra("inventoryNo");
        tvCardNumber.setText(cardNumber);
        tvInventoryNo.setText(inventoryNo);
        //查询当前实物码资产信息数据并赋值到成员变量faCardInfo数组map中
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("psncode", cardNumber);
            jsonObject.put("facardcode", cardNumber);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        //参数{"psncode":"As210420113","facardcode":"As210420113"}(鬼接口一定要这样吗？)
        queryAssets(jsonObject);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_save:
                save();
                break;
            case R.id.go_back:
            case R.id.bt_cancel:
                finish();
                break;
        }

    }

    //组件初始化
    private void initAssembly() {
        //单号
        tvInventoryNo = findViewById(R.id.tv_inventoryNo);
        //实物码
        tvCardNumber = findViewById(R.id.tv_card_number);
        //保存按钮
        btSave = findViewById(R.id.bt_save);
        btSave.setOnClickListener(this);
        //位置下拉框
        atvLocationNumber = findViewById(R.id.atv_location_number);
        //位置下拉框数据
        querySpinner(null, null);
        //箭头返回
        goBack = findViewById(R.id.go_back);
        goBack.setOnClickListener(this);
        //取消
        btCancel = findViewById(R.id.bt_cancel);
        btCancel.setOnClickListener(this);
    }


    /**
     * 保存数据
     */
    protected void save() {

        /*参数校验*/
        if (locationArray == null) {
            return;
        }

        if (StringUtils.isEmpty(atvLocationNumber.getText().toString())) {
            Toast.makeText(this, "位置编号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!locationArray.contains(atvLocationNumber.getText().toString())) {
            Toast.makeText(this, "位置编号在系统中不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        //禁用提交按钮
        btSave.setEnabled(false);

        //位置数据
        String location = atvLocationNumber.getText().toString();

        //组装参数
        JSONObject jsonObject = null;
        Map assetsMap = new HashMap();
        try {
            jsonObject = new JSONObject();
            List<String> facardidList = new ArrayList<>();
            String[] split = location.split(BusinessConstants.SEPARATOR);
            if (split != null && split.length == 2) {
                assetsMap.put("field_6887600017540911109", split[0]);
                assetsMap.put("field_6887600017549299712", split[1]);
            }

            List<Map<String, Object>> dataList = new ArrayList<>();
            Map<String, Object> stringObjectHashMap = new HashMap<>();
            Map<String, Object> faCard = faCardInfo.get(0);
            facardidList.add(faCard.get("facardid") == null ? "" : faCard.get("facardid").toString());
            stringObjectHashMap.put("id", faCard.get("facardid") == null ? "" : faCard.get("facardid").toString());
            stringObjectHashMap.put("num", faCard.get("num") == null ? "" : faCard.get("num").toString());
            dataList.add(stringObjectHashMap);

            jsonObject.put("dataIds", JsonUtil.toJSONArray(facardidList));
            jsonObject.put("data", JsonUtil.toJSONArray(dataList));
            jsonObject.put("maindata", JsonUtil.toJSONObject(assetsMap));
            jsonObject.put("userid", SaveData.getString(this, "userid"));
            jsonObject.put("username", SaveData.getString(this, "userName"));

            Log.v("jsonObject资产信息提交", jsonObject.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog("提示", "提交中...");

        service.post(jsonObject, HttpUrlComstants.MODIFY_BINDING_LOCATION, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                //ToastUtils.makeText(UpdateLocationActivity.this, response.optString("message"), ToastUtils.LENGTH_LONG).show();
                JSONObject jsonObject2 = new JSONObject();
                //盘点单号
                try {
                    String inventoryNo = tvInventoryNo.getText().toString();
                    String cardNumber = tvCardNumber.getText().toString();
                    jsonObject2.put("inventoryNo", inventoryNo);
                    jsonObject2.put("cardNumber", cardNumber);
                    jsonObject2.put("def1", "");
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                //同步资产信息
                service.post(jsonObject2, HttpUrlComstants.SYNC_FA_CARD, new JsonSuccessListener() {
                    @Override
                    public void onRespone(String msg, JSONObject response) {

                        Intent intent = new Intent(UpdateLocationActivity.this, IndexActivity.class);
                        //[{"a":{"resultData":[{"jsonStr":"{\"field_6887600017549299712\":\"一期工业园办公楼10F1044\",\"field_6887600017540911109\":\"Q1-B3-10F-1044\"}"}],"resultFlag":1,"resultMessage":"更新成功"}}]
                        String[] split = location.split(BusinessConstants.SEPARATOR);
                        intent.putExtra("location", split[1]);
                        setResult(11, intent);
                        //退出当前页面
                        finish();
                    }
                }, new JsonFailuredListener() {
                    @Override
                    public void onRespone(String msg, JSONObject response) {
                        Log.e("error", response.optString("message"));
                    }
                });

            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
            }
        });
        hideProgressDialog();
    }

    /**
     * 查询位置--下拉数据
     *
     * @param position
     * @param cost
     * @return void
     * @author: zhongfan
     * @Date 2022/2/15 21:00
     **/
    private void querySpinner(String position, String cost) {

        locationArray = new ArrayList<>();
        /*查询位置信息*/
        service.post(new JSONObject(), HttpUrlComstants.QUERY_LOCATION_INFORMATION, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

                try {
                    JSONArray centerinfo = JsonUtil.getJsonObjectArray(response, "locationinfo", UpdateLocationActivity.this);
                    if (centerinfo != null && centerinfo.length() > 0) {
                        for (int i = 0; i < centerinfo.length(); i++) {
                            if (centerinfo.get(i) == null) {
                                continue;
                            }
                            JSONObject jsonObject = new JSONObject(centerinfo.get(i).toString());
                            if (jsonObject.get("location") == null && jsonObject.get("locationname") != null) {
                                continue;
                            }
                            locationArray.add(jsonObject.optString("location") + BusinessConstants.SEPARATOR + jsonObject.optString("locationname"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                setATVData(locationArray, atvLocationNumber);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(UpdateLocationActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 位置信息下拉框设置
     *
     * @param data
     * @param atc
     */
    private void setATVData(List<String> data, AutoCompleteTextView atc) {
        AutoCompleteTextViewAdapter actvAdapter = new AutoCompleteTextViewAdapter(this, R.layout.item_select, data);
        atc.setAdapter(actvAdapter);
        atc.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                AutoCompleteTextView view = (AutoCompleteTextView) v;
                if (hasFocus) {
                    view.showDropDown();
                }
            }
        });
        atc.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                AutoCompleteTextView view = (AutoCompleteTextView) v;
                view.showDropDown();
                return false;
            }
        });
    }

    /**
     * 查询资产并赋值到成员变量faCardInfo中
     */
    private void queryAssets(JSONObject jsonObject) {
        service.post(jsonObject, HttpUrlComstants.QUERY_ASSET_DETAILS, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

                JSONObject jsonObject = null;
                try {
                    jsonObject = JsonUtil.getJsonObject(response, "facardinfo", UpdateLocationActivity.this);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonObject == null) {
                    tvCardNumber.setText("资产系统不存在");
                    return;
                }

                Map<String, Object> map = new HashMap<>();
                map.put("facardcode", jsonObject.optString("facardcode") == null ? "" : jsonObject.optString("facardcode").toString());
                map.put("maname", jsonObject.optString("maname") == null ? "" : jsonObject.optString("maname").toString());
                map.put("manumber", jsonObject.optString("manumber") == null ? "" : jsonObject.optString("manumber").toString());
                map.put("facardid", jsonObject.optString("facardid") == null ? "" : jsonObject.optString("facardid"));
                map.put("num", jsonObject.optString("num") == null ? 0 : jsonObject.optString("num"));
                faCardInfo.add(map);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
            }
        });
    }

    /**
     * 提示加载
     */
    public void showProgressDialog(String title, String message) {
        if (progressDialog == null) {
            progressDialog = ProgressDialog.show(UpdateLocationActivity.this, title, message, true, false);
        } else if (progressDialog.isShowing()) {
            progressDialog.setTitle(title);
            progressDialog.setMessage(message);
        }

        progressDialog.show();

    }

    /**
     * 隐藏提示加载
     */
    public void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}
